using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using VotingSystem.Data;
using VotingSystem.Models;
using VotingSystem.Services;

namespace VotingSystem.Controllers
{
    public class VotesController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly PdfExportService _pdfExportService;
        private readonly ExcelExportService _excelExportService;

        public VotesController(
            ApplicationDbContext context,
            UserManager<ApplicationUser> userManager,
            PdfExportService pdfExportService,
            ExcelExportService excelExportService)
        {
            _context = context;
            _userManager = userManager;
            _pdfExportService = pdfExportService;
            _excelExportService = excelExportService;
        }

        [HttpGet]
        public async Task<IActionResult> Export(int id, string format = "pdf")
        {
            var vote = await _context.Votes
                .Include(v => v.Options)
                .Include(v => v.Records)
                    .ThenInclude(r => r.User)
                .FirstOrDefaultAsync(v => v.Id == id);

            if (vote == null)
            {
                return NotFound();
            }

            byte[] fileBytes;
            string contentType;
            string fileExtension;

            switch (format.ToLower())
            {
                case "excel":
                    fileBytes = _excelExportService.ExportVoteToExcel(vote);
                    contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    fileExtension = "xlsx";
                    break;
                case "pdf":
                default:
                    fileBytes = _pdfExportService.ExportVoteToPdf(vote);
                    contentType = "application/pdf";
                    fileExtension = "pdf";
                    break;
            }

            return File(fileBytes, contentType, $"{vote.Title}.{fileExtension}");
        }
    }
} 